<template>
  <a-row :gutter="10">
    <a-col :md="leftColMd" :sm="24" style="margin-bottom: 20px">
      <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="8">
                <a-form-item label="产线" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <j-dict-select-tag type="list" v-model="queryParam.line" dictCode="mes_line_cfg,NAME,LINE"
                                     placeholder="请选择产线或产线组" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-item label="工站" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <op-select placeholder="请选择工站" v-model="queryParam.op" :line="queryParam.line"></op-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-item label="工单号" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <a-input placeholder="" v-model="queryParam.woid"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-item label="班组日期" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <a-date-picker valueFormat="YYYY-MM-DD" placeholder="请选择班组日期" v-model="queryParam.shiftDate"
                                 style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-item label="班组" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <ShiftSelect placeholder="请选择班组" v-model="queryParam.shift"
                               :line="queryParam.line"></ShiftSelect>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="8">
                <a-form-item label="检验员" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                  <a-input placeholder="" v-model="queryParam.user" style="width: 100%"></a-input>
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="7" :md="4" :sm="4">
                <a-form-item label="开始时间">
                  <j-date placeholder="开始时间" v-model="queryParam.sDate" :showTime="true"
                          dateFormat="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :xl="6" :lg="7" :md="4" :sm="4">
                <a-form-item label="结束时间">
                  <j-date placeholder="结束时间" v-model="queryParam.eDate" :showTime="true"
                          dateFormat="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="12" :sm="24">
               <a-button type="primary" @click="searchQuery" icon="search" style="margin-left: 21px">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a-button type="primary" @click="exportXls('不良录入数据导出','')" icon="download"
                        style="margin-left: 8px">导出</a-button>
            </a-col>
          </span>
            </a-row>
          </a-form>
        </div>

        <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
          <i class="anticon anticon-info-circle ant-alert-icon">
          </i> 已选择 <a><b>{{ selectedRowKeys1.length }}</b></a>项
          <a style="margin-left: 24px" @click="onClearSelected1">清空</a>
        </div>

        <div style="margin-top: 15px">
          <a-table
            style="height:500px"
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys1, onChange: onSelectChange1, type:'radio'}"
            @change="handleTableChange">
          <span slot="action" slot-scope="text, record">
            <a @click="handleOpen(record)">详情</a>
            <a-divider type="vertical" />
            <a @click="exportXls('不良录入数据导出',record)">导出</a>
        </span>
          </a-table>
        </div>
      </a-card>
    </a-col>
    <a-col :md="rightColMd" :sm="24" v-if="this.rightcolval == 1">
      <a-card :bordered="false">
        <div style="text-align: right;">
          <a-icon type="close-circle" @click="hideUserList" />
        </div>
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :md="12" :sm="12">
                <a-form-item label="序列号">
                  <a-input placeholder="" v-model="queryParam.unitsn"></a-input>
                </a-form-item>
              </a-col>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="9" :sm="24">
             <a-button type="primary" @click="searchQuery2" icon="search" style="margin-left: 21px">查询</a-button>
              <a-button type="primary" @click="searchReset2" icon="reload" style="margin-left: 8px">重置</a-button>
              <a-button type="primary" @click="openChangeFrom" icon="edit" v-has="'AdverseStatistics:edit'"
                        style="margin-left: 8px">更改不良结果</a-button>
              <a-button type="primary" @click="handleDelete1" icon="edit" v-has="'AdverseStatistics:edit'"
                        style="margin-left: 8px">批量删除</a-button>
            </a-col>
          </span>
            </a-row>
          </a-form>
        </div>
        <!-- table区域-begin -->
        <div>
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
              selectedRowKeys2.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected2">清空</a>
          </div>
          <a-table
            style="height:500px"
            ref="table2"
            bordered
            size="middle"
            rowKey="id"
            :columns="columns2"
            :dataSource="dataSource2"
            :pagination="ipagination2"
            :loading="loading2"
            :rowSelection="{selectedRowKeys: selectedRowKeys2, onChange: onSelectChange2}"
            @change="handleTableChange2">
           <span slot="action" slot-scope="text, record">
                  <a @click="handleDelete2(record)" v-has="'AdverseStatistics:edit'">删除</a>
        </span>
          </a-table>
        </div>
        <j-modal
          :title="title"
          :width="width"
          :visible="visible"
          :confirmLoading="confirmLoading"
          switchFullscreen
          @ok="changeOk"
          @cancel="changeCancel"
          cancelText="关闭">
          <a-spin :spinning="confirmLoading">
            <a-form-model ref="form" :model="model" :rules="validatorRules">
              <a-row>
                <a-col :span="24">
                  <a-form-model-item label="不良描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="cfgid">
                    <a-select
                      v-model="model.cfgid"
                      show-search
                      placeholder="缺陷描述"
                      :options="cfgOptions"
                      :filter-option="filterOption"
                    ></a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item label="处理方案" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="typ">
                    <a-select
                      ref="select"
                      v-model="model.typ"
                      placeholder="请选择处理方案"
                      :disabled="true"
                    >
                      <a-select-option value="3">报废</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </a-spin>
        </j-modal>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { deleteAction, postAction, getAction, downFile, httpAction } from '@/api/manage'
import { filterObj } from '@/utils/util'
import OpSelect from '@comp/mes/OpSelect.vue'
import ShiftSelect from '@comp/mes/ShiftSelect.vue'
import moment from 'moment'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'

export default {
  name: 'AdverseStatistics',
  mixins: [JeecgListMixin],
  components: {
    OpSelect,
    ShiftSelect,
    moment
  },
  data() {
    return {
      title: '不良原因更改',
      width: 800,
      visible: false,
      confirmLoading: false,
      cfgOptions: [],
      validatorRules: {
        cfgid: [
          { required: true, message: '请选择不良原因!' }
        ]
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: {},
      model1: {},
      model2: {},
      currentRoleId: '',
      currentCfgId: '',
      queryParam1: {},
      queryParam2: {},
      dataSource1: [],
      dataSource2: [],
      ipagination1: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      ipagination2: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      isorter1: {
        column: 'createTime',
        order: 'desc'
      },
      isorter2: {
        column: 'createTime',
        order: 'desc'
      },
      filters1: {},
      filters2: {},
      loading1: false,
      loading2: false,
      selectedRowKeys1: [],
      selectedRowKeys2: [],
      selectionRows1: [],
      selectionRows2: [],
      test: {},
      rightcolval: 0,
      columns:
        [
          {
            title: '产线',
            align: 'center',
            dataIndex: 'line'
          },
          {
            title: '工站',
            align: 'center',
            dataIndex: 'op'
          },
          {
            title: '不良描述',
            align: 'center',
            dataIndex: 'description'
          },
          {
            title: '数量',
            align: 'center',
            dataIndex: 'num'
          },
          {
            title: '错误代码',
            align: 'center',
            dataIndex: 'dc'
          },
          {
            title: '操作',
            dataIndex: 'action',
            width: 100,
            align: 'center',
            scopedSlots: { customRender: 'action' }
          }
        ],
      columns2: [
        {
          title: '工单ID',
          align: 'center',
          dataIndex: 'woid'
        },
        {
          title: '序列号',
          align: 'center',
          dataIndex: 'unitsn'
        },
        {
          title: '处理方案',
          align: 'center',
          dataIndex: 'type_dictText'
        },
        {
          title: '录入时间',
          align: 'center',
          dataIndex: 'ctime'
        },
        {
          title: '班次日期',
          align: 'center',
          dataIndex: 'shiftDate'
        },
        {
          title: '班次',
          align: 'center',
          dataIndex: 'shift'
        },
        {
          title: '创建人',
          align: 'center',
          dataIndex: 'user'
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: 120
        }],

      // 高级查询参数
      superQueryParams2: '',
      // 高级查询拼接条件
      superQueryMatchType2: 'and',
      runCmd: '/monitor/api/runCmd',
      url: {
        list: '/trace/faultStatistics/list',
        list2: '/trace/qisReinspectValue/list',
        cfgList: '/qis/qisReinspectCfg/list',
        addUserRole: '/sys/user/addSysUserRole',
        delete2: '/trace/qisReinspectValue/delete',
        deleteBatch2: '/trace/qisReinspectValue/deleteBatch',
        exportXlsUrl: '/trace/faultStatistics/exportXls2',
        importExcelUrl: 'sys/role/importExcel'
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    leftColMd() {
      return this.selectedRowKeys1.length === 0 ? 24 : 8
    },
    rightColMd() {
      return this.selectedRowKeys1.length === 0 ? 0 : 16
    }
  },
  methods: {
    opChange() {
      //清空下边所有选项
      this.model.cfgid = ''
      this.model.typ = null
      this.model.code = null
      //访问对应产线对应工站的所有故障描述并展示
      let param = {
        line: this.model1.line,
        op: this.model1.op,
        pageNo: 1,
        pageSize: 100
      }
      getAction(this.url.cfgList, param).then((res) => {
        //将数据存放在数组中
        let option = []
        res.result.records.map(item => {
          option.push({
            value: item.recId,
            label: item.description
          })
        })
        this.cfgOptions = option
        this.cfgOptionDetails = res.result.records
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.indexOf(input) !== -1
    },
    changeOk() {
      const that = this
      that.confirmLoading = true
      console.log('提交')
      console.log(this.selectionRows2)
     let rows =  that.selectionRows2
      rows.map(item => {
            this.gotoScrap(item.unitsn)
          })
      // this.selectionRows2.map(item => {
      //   this.gotoScrap(item.unitsn)
      // })
      that.confirmLoading = false
      that.visible =false
    },
    gotoScrap(code) {
      console.log('更改为报废')
      const that = this
      let load = {
        serviceid: 'mes',
        cmd: 'rework',
        entityid: code,
        clientid: that.model1.line,
        dc: that.model.cfgid,
        user: Vue.ls.get(USER_INFO).username,
        Single: '1',
        code: that.model1.op + '->SCRAP'
      }
      console.log(load)
      httpAction(this.runCmd, load, 'post').then((res) => {
        if (res.success) {
          if (res.result.errorCode === 'OK') {
            that.$message.success('操作成功！')
          }
        } else {
          that.$message.warn(res.message)
        }
      }).finally(() => {
      })
    },
    gotoRelease(code) {
      const that = this
      let load = {
        serviceid: 'mes',
        cmd: 'Release',
        entityid: code,
        clientid: that.model1.line,
        user: Vue.ls.get(USER_INFO).username,
        Single: '1'
      }
      httpAction(this.runCmd, load, 'post').then((res) => {
        if (res.success) {
          if (res.result.errorCode === 'OK') {
            that.$message.success('操作成功！')
          }
        } else {
        }
      }).finally(() => {
      })
    },
    changeCancel() {
      this.visible = false
      this.$refs.form.clearValidate()
    },
    exportXls(fileName, record) {
      this.loading = true
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams2()
      if (record) {
        this.currentCfgId = record.cfgId
        param.cfgid = this.currentCfgId
      }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
      })
      this.loading = false
    },
    dateChange(val) {
      console.log('变更')
      console.log(val)
      this.queryParam.sDate = val[0].format('YYYY-MM-DD')
      this.queryParam.eDate = val[1].format('YYYY-MM-DD')
    },
    onSelectChange2(selectedRowKeys, selectionRows) {
      console.log('选中')
      console.log(selectionRows)
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    onClearSelected2() {
      this.selectedRowKeys2 = []
      this.selectionRows2 = []
    },
    onClearSelected1() {
      this.selectedRowKeys1 = []
      this.selectionRows1 = []
    },
    onSelectChange1(selectedRowKeys, selectionRows) {
      this.rightcolval = 1
      this.selectedRowKeys1 = selectedRowKeys
      this.selectionRows1 = selectionRows
      this.model1 = Object.assign({}, selectionRows[0])
      console.log(this.model1)
      this.currentRoleId = selectedRowKeys[0]
      this.loadData2()
    },
    onClearSelected() {
    },

    getQueryParams2() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams2) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams2)
        sqp['superQueryMatchType'] = this.superQueryMatchType2
      }
      var param = Object.assign(sqp, this.queryParam2, this.queryParam)
      param.pageNo = this.ipagination2.current
      param.pageSize = this.ipagination2.pageSize
      return filterObj(param)
    },
    getQueryField2() {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns2.forEach(function(value) {
        str += ',' + value.dataIndex
      })
      return str
    },
    handleEdit2: function(record) {
      this.$refs.modalForm2.title = '编辑'
      this.$refs.modalForm2.roleDisabled = true
      this.$refs.modalForm2.edit(record)
    },
    handleAdd2: function() {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.modalForm2.roleDisabled = true
        this.$refs.modalForm2.title = '新增'
        this.$refs.modalForm2.edit({ activitiSync: '1', userIdentity: 1, selectedroles: this.currentRoleId })
      }
    },
    modalFormOk2() {
      // 新增/修改 成功时，重载列表
      this.loadData2()
    },
    loadData2(arg) {
      if (!this.url.list2) {
        this.$message.error('请设置url.list2属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      // if (arg === 1) {
      //   this.ipagination2.current = 1
      // }
      if (this.currentCfgId === '') return
      let params = this.getQueryParams()//查询条件
      params.cfgid = this.currentCfgId
      params.pageNo = this.ipagination2.current
      params.pageSize = this.ipagination2.pageSize
      this.loading2 = true
      getAction(this.url.list2, params).then((res) => {
        if (res.success) {
          this.dataSource2 = res.result.records
          this.ipagination2.total = res.result.total
        }
        this.loading2 = false
      })

    },
    handleDelete1() {
      let selectionRows = this.selectionRows2
      var that = this
      if (selectionRows){
        postAction(that.url.deleteBatch2, selectionRows).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.loadData2()
            this.loadData(1)
          } else {
            that.$message.warning(res.message)
          }
        })
      }
      this.handleDelete(id)
      this.dataSource2 = []
      this.currentRoleId = ''
    },
    handleDelete2: function(param) {
      if (!this.url.delete2) {
        this.$message.error('请设置url.delete2属性!')
        return
      }
      var that = this
      postAction(that.url.delete2, param).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData2()
          this.loadData(1)
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    batchDel2: function() {

      if (!this.url.deleteBatch2) {
        this.$message.error('请设置url.deleteBatch2属性!')
        return
      }
      if (this.selectedRowKeys2.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys2.length; a++) {
          ids += this.selectedRowKeys2[a] + ','
        }
        var that = this
        console.log(this.currentDeptId)
        this.$confirm({
          title: '确认取消关联',
          content: '是否删除选中数据?',
          onOk: function() {
            deleteAction(that.url.deleteBatch2, { roleId: that.currentRoleId, userIds: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData2()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    selectOK(data) {
      let params = {}
      params.roleId = this.currentRoleId
      params.userIdList = []
      for (var a = 0; a < data.length; a++) {
        params.userIdList.push(data[a])
      }
      console.log(params)
      postAction(this.url.addUserRole, params).then((res) => {
        if (res.success) {
          this.loadData2()
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
      })
    },

    handleAddUserRole() {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.selectUserModal.visible = true
      }
    },
    handleOpen(record) {
      this.rightcolval = 1
      this.selectedRowKeys1 = [record.cfgId]
      this.model1 = Object.assign({}, record)
      this.ipagination2.current = 1
      this.currentCfgId = record.cfgId
      this.onClearSelected2()
      this.loadData2()
    },
    /*handleEdit: function(record) {
      if (this.currentRoleId == '') {
        this.$message.error('请选择一个角色!')
      } else {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
      }
    },*/
    searchQuery2() {
      this.loadData2(1)
    },
    openChangeFrom() {
      if (this.selectionRows2.length < 1) {
        this.$message.warning('请至少选择一条数据!')
        return
      }
      this.opChange()
      this.model = {}
      this.model.typ = '3'
      this.visible = true
      this.disableSubmit = false
    },
    searchReset2() {
      this.queryParam2 = {}
      this.loadData2(1)
    },
    handleTableChange2(pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter2.column = sorter.field
        this.isorter2.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination2 = pagination
      this.loadData2()
    },
    hideUserList() {
      //this.rightcolval = 0
      this.selectedRowKeys1 = []
    },
    handlePerssion(roleId) {
      this.$refs.modalUserRole.show(roleId)
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
/** Button按钮间距 */
.ant-btn {
  margin-left: 8px
}
</style>